package com.lianniu.web.staff.controller;

import com.lianniu.web.base.BaseResult;
import com.lianniu.web.baseService.user.model.FrontUserVo;
import com.lianniu.web.baseService.user.service.IFrontUserService;
import com.lianniu.web.baseService.user.service.ISupplyService;
import com.lianniu.web.baseService.user.service.impl.FrontUserServiceImpl;
import com.lianniu.web.buyerOrder.model.OrderDetailVo;
import com.lianniu.web.buyerOrder.model.OrderInfoVo;
import com.lianniu.web.operationMessage.service.OperMessageService;
import com.lianniu.web.operationMessage.vo.OperMessage;
import com.lianniu.web.staff.service.StaffClientService;
import com.lianniu.web.staff.service.StaffOrderService;
import com.lianniu.web.staff.service.StaffProductService;
import com.lianniu.web.staff.service.StaffService;
import com.lianniu.web.staff.vo.Staff;
import com.lianniu.web.util.MD5Util;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.Date;

/**
 * Created by Administrator on 2017-05-16.
 */
@Controller
@RequestMapping("/rest/staff")
public class StaffRestController {

    private final static Logger logger = Logger.getLogger(StaffRestController.class);
    @Autowired
    StaffService staffService;

    @Autowired
    StaffProductService staffProductService;

    @Autowired
    StaffClientService staffClientService;

    @Autowired
    StaffOrderService staffOrderService;

    @Autowired
    IFrontUserService frontUserService;

    @Autowired
    ISupplyService supplyService;

    @Autowired
    OperMessageService operMessageService;

    @RequestMapping(value = {"/login"}, method = RequestMethod.POST)
    @ResponseBody
    public BaseResult userLogin(HttpServletRequest request, String username,
                                String userpasswd, String codeUuid, String code, int times) {
        logger.info("StaffRestController userLogin begin.");
        BaseResult baseResult = staffService.login(request, username, userpasswd, codeUuid, code, times);
        logger.info("StaffRestController userLogin end.");
        return baseResult;
    }

    @RequestMapping("/staffIndex")
    @ResponseBody
    public BaseResult getList(String userId, String pageNum) {
        int page = 0;
        if (!StringUtils.isBlank(pageNum)) {
            page = Integer.valueOf(pageNum);
        }
        return this.staffProductService.getList(userId, page);
    }

    @RequestMapping("myClients")
    @ResponseBody
    public BaseResult getClient(String userId, String pageNum) {
        int page = 0;
        if (!StringUtils.isBlank(pageNum)) {
            page = Integer.valueOf(pageNum);
        }
        return this.staffClientService.getClient(userId, page);
    }

    @RequestMapping("orders")
    @ResponseBody
    public BaseResult getOrders(String staffId, String approveStatus, String pageNum) {
        int page = 0;
        if (!StringUtils.isBlank(pageNum)) {
            page = Integer.valueOf(pageNum);
        }
        return this.staffOrderService.getOrders(staffId, approveStatus, page);
    }

    @RequestMapping("/orderDetail")
    @ResponseBody
    public BaseResult getOrderDetail(String orderId) {
        return this.staffOrderService.getOrderById(orderId);
    }

    @RequestMapping("/updateOrder")
    @ResponseBody
    public BaseResult updateOrder(String userId, OrderInfoVo orderInfoVo, OrderDetailVo orderDetailVo) {
        orderDetailVo.setModifyUser(userId);
        orderDetailVo.setModifyTime(new Date());
        orderDetailVo.setPrice(new BigDecimal(orderDetailVo.getActProductNum()).multiply(new BigDecimal(orderDetailVo.getActPrice())).toPlainString());
        orderDetailVo.setOrderID(orderInfoVo.getId());
        orderInfoVo.setModifyTime(new Date());
        orderInfoVo.setModifyUser(userId);
        orderInfoVo.setRecvPrice(new BigDecimal(orderDetailVo.getPrice())
                .add(new BigDecimal(orderInfoVo.getServiceFee()))
                .add(new BigDecimal(orderInfoVo.getChargeFee())).toPlainString());

        this.staffOrderService.updateOrderDetail(orderDetailVo);
        this.staffOrderService.updateOrderInfo(orderInfoVo);
        try {
            OperMessage operMessage = new OperMessage();
            operMessage.setCreatetime(new Date());
            operMessage.setDelflag("1");
            operMessage.setStatus("1");
            operMessage.setSalespersonid(userId);
            operMessage.setOrderid(Long.valueOf(orderInfoVo.getId()));
            operMessage.setType(OperMessage.TYPE_STAFF_MODIFY_PRODUCT);
            operMessage.setSource(OperMessage.RESOURCE_STAFF);
            operMessage.setIsread("1");
            operMessageService.insertSelective(operMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BaseResult.success();
    }

    @RequestMapping("/offShelf")
    @ResponseBody
    public BaseResult offShelf(String id,String staffId) {
        this.staffProductService.offShelf(id, staffId);
        try {
            OperMessage operMessage = new OperMessage();
            operMessage.setCreatetime(new Date());
            operMessage.setDelflag("1");
            operMessage.setStatus("1");
            operMessage.setSalespersonid(staffId);
            operMessage.setSkuproductid(Long.valueOf(id));
            operMessage.setType(OperMessage.TYPE_PRODUCT_OFFSHELF);
            operMessage.setSource(OperMessage.RESOURCE_STAFF);
            operMessage.setIsread("1");
            operMessageService.insertSelective(operMessage);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return BaseResult.success();
    }

    @RequestMapping("/updateSku")
    @ResponseBody
    public BaseResult updateSku(String id,String price,String stock,String userId) {
        this.staffProductService.updateSku(id, price, stock, userId);
        return BaseResult.success();
    }

    @RequestMapping("/supply")
    @ResponseBody
    public BaseResult getSupply(String phone) {
        BaseResult user = frontUserService.getUserByUserName(phone);
        if(user.getData() == null) {
            return BaseResult.fail("0001", "不存在该用户");
        }
        FrontUserVo frontUserVo = (FrontUserVo) user.getData();
        BaseResult supply = supplyService.selectByUsersId(frontUserVo.getUsersId().toString());
        if(supply.getData() == null) {
            return BaseResult.fail("0001", "不存在该用户");
        }
        return BaseResult.success(user.getData());
    }

    @RequestMapping("/information")
    @ResponseBody
    public BaseResult information(String staffId) {
       return staffService.selectByPrimaryKey(staffId);
    }

    @RequestMapping("changePass")
    @ResponseBody
    public BaseResult changePass(String id,String old,String now){
        if(StringUtils.isBlank(old) || StringUtils.isBlank(now)) {
            return BaseResult.fail("0001", "密码为空");
        }
        Staff staff = (Staff)staffService.selectByPrimaryKey(id).getData();
        if (!staff.getLoginPassword().equals(MD5Util.getMD5String(old))) {
            return BaseResult.fail("0001", "原密码不正确");
        }

        Staff param = new Staff();
        param.setId(id);
        param.setLoginPassword(MD5Util.getMD5String(now));
        staffService.updateByPrimaryKeySelective(param);
        return BaseResult.success();
    }
}

